<template>
  <el-menu
    :default-active="activeIndex"
    class="el-menu-demo"
    mode="horizontal"
    :ellipsis="false"
    @select="handleSelect"
    style="display: flex; align-items: center; justify-content: space-between;"
  >
    <div class="menu-left" style="display: flex; align-items: center;">
      <el-menu-item index="0">
        <h1 style="margin: 0;">书单之家</h1>
      </el-menu-item>
    </div>

    <!-- 中间部分：搜索框 -->
    <div class="menu-center" style="flex-grow: 1; text-align: center; display: flex; align-items: center;">
      <span style="width: 24%;"> </span>
      <el-select v-model="searchType" placeholder="选择搜索类型" style="margin-right: 10px; width: 100px">
        <el-option label="书单" value="booklist"></el-option>
        <el-option label="用户" value="user"></el-option>
        <el-option label="书本" value="book"></el-option>
        <el-option label="标签" value="category"></el-option>
      </el-select>
      <el-input
        v-model="input"
        style="width: 600px"
        placeholder="搜索内容"
        class="input-with-select"
      >
        <template #append>
          <el-button :icon="Search" @click="searchContent">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 右边部分：菜单选项 -->
    <div class="menu-right" style="display: flex; align-items: center;">
      <el-menu-item index="1">我的书单</el-menu-item>
      <el-sub-menu index="2">
        <template #title>欢迎你 {{ userStore.userInfo.name }}</template>
        <el-menu-item index="2-1" @click="manageUser">管理账户</el-menu-item>
        <el-menu-item index="2-2" @click="manageBlogs">管理我的书单</el-menu-item>
        <el-menu-item index="2-3" @click="logout()">退出登录</el-menu-item>
      </el-sub-menu>
    </div>
  </el-menu>

  <!-- 用户搜索结果抽屉 -->
  <el-drawer v-model="userDrawerVisible" title="用户搜索结果" size="40%">
  <div v-if="users.length">
    <div v-for="(user, index) in users" :key="index" class="comment-item">
      <p>用户 ID: {{ user.id }}</p>
      <p>姓名: {{ user.name }}</p>
      <p>性别: {{ user.gender }}</p>
      <p>年龄: {{ user.age }}</p>
      <p>邮箱: {{ user.email }}</p>
      <!-- 添加查看书单的按钮 -->
      <el-button
        type="primary"
        size="small"
        @click="viewUserBooklist(user.id)"
        style="margin-top: 10px;"
      >
        查看书单
      </el-button>
      <el-divider></el-divider>
    </div>
  </div>
  <div v-else>
    <p>未找到相关用户</p>
  </div>
</el-drawer>
<div></div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { useUserStore } from '../plugins/pinia';
import { ElMessageBox, ElMessage } from 'element-plus';

const emit = defineEmits(['navigateToUserBlogs', 'navigateToUser', 'updateBlogs']);

const input = ref('');
const searchType = ref('booklist'); // 搜索类型，初始为书单
const activeIndex = ref('1');
const userStore = useUserStore();
const userId = userStore.userInfo.id;

const userDrawerVisible = ref(false);
const commentDrawerVisible = ref(false);
const users = ref([]);
const comments = ref([]);

const { proxy } = getCurrentInstance();

// 判断是否登录
const checkLogin = async (callback) => {
  if (userId === 0) {
    // 提示用户登录
    try {
      await ElMessageBox.confirm(
        '请登录后再继续操作',
        '提示',
        {
          confirmButtonText: '登录',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );
      // 跳转到登录页面
      proxy.$router.push('/login'); // 假设登录页面的路由是 /login
    } catch {
      ElMessage.info('操作已取消');
    }
    return false; // 阻止后续事件
  }
  return true; // 用户已登录，可以继续
};

const viewUserBooklist = async (userId) => {
  try {
    const response = await proxy.$axios.get(`/recommend/user/${userId}`);
    if (response.data.data) {
      emit('updaterecommend', response.data.data); // 通过事件将数据传递给父组件
      userDrawerVisible.value = false; // 关闭用户搜索结果抽屉
      proxy.$message.success('已加载用户的书单');
    } else {
      proxy.$message.warning('该用户未创建任何书单');
    }
  } catch (error) {
    console.error('Error fetching user booklist:', error);
    proxy.$message.error('加载用户书单失败，请稍后重试');
  }
};

// 搜索内容的函数
const searchContent = async () => {
  if (!input.value.trim()) {
    emit('updateBlogs', []);
    proxy.$message.warning('请输入要搜索的内容');
    return;
  }

  try {
    let response;
    let url;

    switch (searchType.value) {
      case 'booklist':
        url = `/recommend/s01/${input.value}`;
        response = await proxy.$axios.get(url);
        if (response.data.data) {
          emit('updaterecommend', response.data.data);
          proxy.$message.success('搜索成功');
        } else {
          emit('updateBlogs', []);
          proxy.$message.warning('没有找到匹配的内容');
        }
        break;

      case 'user':
        url = `/user/${input.value}`;
        response = await proxy.$axios.get(url);
        if (response.data.data) {
          users.value = response.data.data;
          userDrawerVisible.value = true;
          proxy.$message.success('搜索成功');
        } else {
          user.value = null;
          userDrawerVisible.value = true;
          proxy.$message.warning('没有找到匹配的用户');
        }
        break;

      case 'book':
        url = `/book/s01/${input.value}`;
        response = await proxy.$axios.get(url);
        if (response.data.data) {
          emit('navigateToBookDisplay', response.data.data);
          proxy.$message.success('搜索成功');
        } else {
          emit('updateBlogs', []);
          proxy.$message.warning('没有找到匹配的图书');
        }
        break;

      case 'category':
        url = `/book/s02/${input.value}`;
        response = await proxy.$axios.get(url);
        if (response.data.data) {
          emit('navigateToBookDisplay', response.data.data);
          proxy.$message.success('搜索成功');
        } else {
          emit('updateBlogs', []);
          proxy.$message.warning('没有找到此标签的图书');
        }
        break;    

      default:
        proxy.$message.error('无效的搜索类型');
        return;
    }
  } catch (error) {
    console.error('Error fetching data:', error);
    proxy.$message.error('搜索过程中出现错误，请稍后重试');
  }
};

// 管理博客
const manageBlogs = async () => {
  if (await checkLogin()) {
    emit('navigateToUserBlogs', userId);
  }
};

// 管理用户
const manageUser = async () => {
  if (await checkLogin()) {
    emit('navigateToUser');
  }
};

// 处理菜单选择事件
const handleSelect = (key, keyPath) => {
  console.log('Selected key:', key, 'KeyPath:', keyPath);
};

// 退出登录
const logout = () => {
  window.location.reload();
};
</script>

<style scoped>
/* 样式增强 */
.el-menu-demo {
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
.menu-center {
  width-max: 200px;
}
.menu-left,
.menu-right {
  white-space: nowrap; /* 防止菜单项折行 */
}
.comment-item {
  padding: 10px 0;
}
</style>
